import React from 'react'
import { SearchBar } from 'antd-mobile'
import Nav from 'components/nav'
import Rate from 'components/rate'
import { get, post } from '../../axios'
import utils from '../../common/utils'
import moment from 'moment'
import history from '../../history'

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {actions} from '../../reducers'
import { actions as UserAction } from '../../reducers/user'
import { actions as SearchAction } from '../../reducers/search'


import './index.less'

const applySetResult = (result) => (prevState) => ({
    hits: result.data,
  });

const getUrl = (value) =>
  `mem/search?keyword=${value}`

const formatResultType = (type) => {
    switch (type) {
        case "username":
        case "title":
        case "publish_username":
            return ''
        case "link_content":
            return '聊天：'
        case "content":
            return '项目信息：'
        case "execute_username":
            return '执行人：'
        case "revision_content":
            return '修订信息：'
        case "progress_content":
            return '进度：'
        default:
            return ""
    }
}

const search_result = (data) => {
    if (['username', 'title', 'publish_username'].includes(data.result_type)) {
        return ''
    }
    return data[data.result_type]
}

class Search extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            hits: [],
        }
    }

    componentDidMount() {
        const referer = document.referrer
        console.log(referer, /.*(profile|project-detail).*/.test(referer))
       
        this.setState({hits: this.props.searchData})
        
        this.props.get_user_info()
    }

    onInitialSearch = (value) => {
        if (value === '') {
          return;
        }
    
        this.fetchStories(value);
      }
    
    fetchStories = (value) =>{
        this.props.update_result([])
        post(getUrl(value))
          .then(resp => {
              if (resp.success) {
                this.onSetResult(resp)
                this.props.update_result(resp.data)
            }
        })
    }

    
    onSetResult = (result) =>
        this.setState(applySetResult(result))
    
    render() {
        console.log(this.state)
        return (
            <div className='search'>
                <SearchBar placeholder="Search" onChange={this.onInitialSearch} ref={node => this.input = node}/>
                <div className='result-wrap '>
                    <List
                        list={this.state.hits}
                        user={this.props.userInfo}
                        update_result={this.props.update_result}
                    />
                </div>
                <Nav/>
            </div>
        )
    }
}

const List = ({list, user, update_result}) => 
    <React.Fragment>
        {
            list.map(x => {
                if (x.search_type==='user') {
                    return <UserItem data={x} update_result={update_result}/>
                } else {
                    return <ProjectItem data={x} user={user} update_result={update_result}/>
                }
            })
        }
    </React.Fragment>

const UserItem = ({data, update_result}) =>
    <div class="soso-row" key={data.id} 
        onClick={()=> history.push(`/contacts/detail/${data.id}`)}
    >
        <div className='col-xs-4'>
            <img src={data.avatar} />
        </div>
        <div class="soso-lt col-xs-8">
            <div class="name">{data.nickname}</div>
            <div className='search_result ellipsis'>{formatResultType(data.result_type)}<span dangerouslySetInnerHTML={{__html:search_result(data)}}></span></div>
            <div class="grade">
                <Rate
                    value={data.rank}
                    count={6}
                    disabled={true}
                />
            </div>
        </div>
    </div>

const ProjectItem  = ({data, user, update_result}) => {
    let role = resolve_role(data, user),
        url = resovle_url(role, data)
    if (!data.category_name) return null;
    
    return <dl className='container' key={data.id} onClick={()=>history.push(url)}>
                <dt className="col-xs-4"><a><img src="https://ceoja-1251886366.cos.ap-guangzhou.myqcloud.com/a1.jpg" /></a></dt>
                <dd className="col-xs-8">
                    <div className="p1">
                    <span>{data.title}</span>
                    <i>{`发布者：${data.publish_username}`}</i>
                    </div>
                    <p className='search_result ellipsis'>{formatResultType(data.result_type)}<span dangerouslySetInnerHTML={{__html:search_result(data)}}></span></p>
                    <div className="p2">
                        <span>
                            <em>{data.type?utils.formatProjectStatus(data.type):utils.formatProjectStatus(data.status)}</em>
                            <i>{data.category_name}</i>
                        </span>
                        <label>{moment(data.created_at).format('YYYY-MM-DD hh:mm')}</label>
                    </div>
                </dd>
            </dl>
}

// 返回项目对于本用户是什么类型
const resolve_role = (data, user) => {
    console.log(data.project_type)
    // if (user.is_admin) return 'admin';
    if (data.project_type=='project') {
        return 'publish'
    }
    if (data.project_type=='project_user' && data.status=='pending') {
        return 'grab'
    } 
    return 'execute'
}

const resovle_url = (role, data) => {
    // if (role=='admin') {
    //     return `/project-detail/introduction/${role}?type=${role}&id=${data.id}&project_id=${data.id}`
    // }
    if (role=='publish' || role=='admin') {
        return `/project-detail/introduction/publish?type=publish&id=${data.id}&project_id=${data.id}`
    }
    
    return `/project-detail/introduction/${role}?type=${role}&id=${data.id}&project_id=${data.project_id}`
        
}


function mapStateToProps(state) {
    return {
      userInfo: state.user.userInfo,
      searchData: state.search.data
    }
}
  
function mapDispatchToProps(dispatch) {
    return  {
        get_user_info: bindActionCreators(UserAction.get_user_info, dispatch),
        update_result: bindActionCreators(SearchAction.update_result, dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Search)